package cn.tedu.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint("/chat/{userId}")
public class WebChatSocketServer {
    private static ConcurrentHashMap<WebChatSocketServer,Session> webSocketMap=new ConcurrentHashMap<>();
    public WebChatSocketServer(){
        log.debug("WebChatSocketServer()");
    }
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session){
        webSocketMap.put(this,session);
        log.debug("有新用户加入！当前连接数：{}",webSocketMap.size());
        broadcastMessage("有新用户"+userId+"加入！");
    }
    @OnMessage
    public void onMessage(String message){
        broadcastMessage(message);
    }
    @OnClose
    public void onClose(Session session){
        webSocketMap.remove(this);
         log.debug("{}连接关闭，用户退出了！",session.getId());
    }
    @OnError
    public void onError(Session session,Throwable e){
        log.error("发生错误:{}",e.getMessage());
    }
    public  void broadcastMessage(String message){
        Collection<Session> sessions = webSocketMap.values();
        for (Session session : sessions) {
            try {
                //session.getBasicRemote().sendText(message);
                session.getAsyncRemote().sendText(message);
            }catch (Exception e){
                e.printStackTrace();
                log.error("发送消息失败！");
            }
        }
    }
}
